var mongodb = require("mongodb");
var MongoClient = mongodb.MongoClient;
var url = "mongodb://127.0.0.1:27017";
var dbName = "vueTest"

// 查找 find
var find = function(client, collection, selector, callback) {
        collection.find(selector).toArray(function(err, data) {
            if (err) throw err;
            console.log("查找成功")
            callback(data);
            client.close();
        })
    }
    // 添加一个
var add = function(client, collection, selector, callback) {
        collection.insertOne(selector, function(err, result) {
            if (err) throw err;
            console.log("增加成功")
            callback(result)
            client.close();
        })
    }
    // 删除一个
var del = function(client, collection, selector, callback) {
        collection.deleteOne(selector, function(err, result) {
            if (err) throw err;
            console.log("删除成功")
            callback(result)
            client.close();
        })
    }
    // 修改一个
var update = function(client, collection, selector, callback) {
        collection.updateOne(selector[0], { $set: selector[1] }, function(err, result) {
            if (err) throw err;
            console.log("修改成功")
            callback(result)
            client.close();
        })
    }
    // 增加多个
var addMany = function(client, collection, selector, callback) {
        collection.insertMany(selector, function(err, result) {
            if (err) throw err;
            console.log("增加多个成功")
            callback(result)
            client.close();
        })
    }
    // 删除多个
var delMany = function(client, collection, selector, callback) {
        collection.deleteMany(selector, function(err, result) {
            if (err) throw err;
            console.log("删除多个成功")
            callback(result)
            client.close();
        })
    }
    // 修改多个
var updateMany = function(client, collection, selector, callback) {
    collection.updateMany(selector[0], { $set: selector[1] }, function(err, result) {
        if (err) throw err;
        console.log("修改多个成功")
        callback(result)
        client.close();
    })
}

var methodType = {
    find: find,
    add: add, //添加一个
    del: del, //删除一个
    update: update, //修改一个
    addMany: addMany, //增加多个
    delMany: delMany, //删除多个
    updateMany: updateMany //修改多个
}
module.exports = function(type, collections, selector, callback) {
    MongoClient.connect(url, function(err, client) {
        var db = client.db(dbName)
        var collection = db.collection(collections) //连接表
        methodType[type](client, collection, selector, callback)
    })
}